import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import { useRef, useState } from 'react';
import {
  createGiftGiving,
  deleteGiftGiving,
  listGiftGivings,
  updateGiftGiving,
} from '@/services/points/api';
import { getByType } from '@/services/sys/dict/api';

const columns: ProColumns<PointsType.GiftGivingList>[] = [
  {
    title: '赠送场景',
    dataIndex: 'type',
    valueType: 'select',
    request: async () => {
      const data = await getByType('points');
      return data.map((item) => ({
        label: item.name,
        value: item.code,
      }));
    },
  },
  {
    title: '赠送条件',
    dataIndex: 'requirement',
    valueType: 'digit',
  },
  {
    title: '赠送积分数',
    dataIndex: 'pointsReward',
    valueType: 'digit',
  },
  {
    title: '当日赠送上限',
    dataIndex: 'bonusPoints',
    valueType: 'digit',
  },
  {
    title: '是否叠加',
    dataIndex: 'isStackable',
    valueType: 'switch',
    fieldProps: {
      checkedChildren: '是',
      unCheckedChildren: '否',
    },
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (_text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.id);
        }}
      >
        编辑
      </a>,
    ],
  },
];

const CreateUserForm = ({
  open,
  onCancel,
  onRefresh,
}: {
  open: boolean;
  onCancel: () => void;
  onRefresh: () => void;
}) => {
  const [form] = Form.useForm();
  // 重置表单
  const resetForm = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <ModalForm<PointsType.GiftGivingCreate>
      title="新建签到规则"
      form={form}
      open={open}
      autoFocusFirstInput
      modalProps={{
        destroyOnHidden: true,
        onCancel: () => {
          console.log('取消新建');
          resetForm();
        },
      }}
      onFinish={async (values) => {
        const createParam = {
          ...values,
          isStackable: values.isStackable ? 1 : 0,
        };
        await createGiftGiving(createParam);
        resetForm();
        onRefresh();
      }}
    >
      <ProForm.Group>
        <ProFormSelect
          name="type"
          label="赠送场景"
          request={async () => {
            const data = await getByType('points');
            return data.map((item) => ({
              label: item.name,
              value: item.code,
            }));
          }}
        />
        <ProFormDigit width="md" name="requirement" label="赠送条件" />
        <ProFormDigit width="md" name="pointsReward" label="赠送积分数" />
        <ProFormDigit width="md" name="bonusPoints" label="当日赠送上限" />
        <ProFormSwitch width="md" name="isStackable" label="是否叠加" />
      </ProForm.Group>
    </ModalForm>
  );
};

export default () => {
  const actionRef = useRef<ActionType>(null);
  const [formVisible, setFormVisible] = useState(false);
  const handleOpenForm = () => setFormVisible(true);
  const handleCloseForm = () => setFormVisible(false);
  return (
    <ProTable<PointsType.GiftGivingList>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      // 获取列表
      request={async (params, _sort, _filter) => {
        const msg = await listGiftGivings({
          ...params,
          pageNum: params.current,
        });
        return {
          data: msg.list,
          success: true,
          total: msg.total,
        };
      }}
      // 编辑列表
      editable={{
        type: 'multiple',
        onSave: async (_key, record, _originRow) => {
          const updateParam = {
            ...record,
            isStackable: record.isStackable ? 1 : 0,
          };

          await updateGiftGiving(updateParam);
          actionRef.current?.reload();
        },
        onDelete: async (_key, row) => {
          await deleteGiftGiving(row.id);
          actionRef.current?.reload();
        },
      }}
      // 列设置
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      search={false}
      options={{
        setting: {
          listsHeight: 400,
        },
      }}
      form={{
        // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 5,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle="赠送规则"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => handleOpenForm()}
          type="primary"
        >
          新建
        </Button>,
        <CreateUserForm
          key="create-form"
          open={formVisible}
          onCancel={handleCloseForm}
          onRefresh={() => actionRef.current?.reload()}
        />,
      ]}
    />
  );
};
